package org.easy.excel.aop.cell.inner;

import java.math.BigDecimal;

import org.easy.excel.aop.cell.CellInterceptorAdapter;
import org.easy.excel.aop.cell.CellJoinPoint;
import org.easy.excel.exception.ExcelException;

/**
 * 处理regex标签(正则)
 * @author lisuo
 *
 */
public class RegexCellInterceptor extends CellInterceptorAdapter {

	@Override
	public boolean supports(CellJoinPoint joinPoint) {
		return joinPoint.getFieldValue().getRegex() != null && joinPoint.getValue() != null;
	}

	@Override
	public Object executeImport(CellJoinPoint joinPoint) throws ExcelException {
		String val;
		if(joinPoint.getValue() instanceof Double) {
			val = doubleToString((Double)joinPoint.getValue());
		}else {
			val = String.valueOf(joinPoint.getValue());
		}
		if (!val.matches(joinPoint.getFieldValue().getRegex())) {
			String msg = joinPoint.getFieldValue().getRegexErrMsg();
			throw newExcelDataException(msg == null ? "格式错误" : msg, joinPoint);
		}
		return super.executeImport(joinPoint);
	}

	private String doubleToString(Double val) {
		return new BigDecimal(String.valueOf(val)).stripTrailingZeros().toPlainString();
	}

}
